import { ApplicationRef, ComponentFactoryResolver, ComponentRef, Injectable, Injector } from '@angular/core';
import { DocumentWrapperService } from './document-wrapper.service';

@Injectable({
  providedIn: 'root'
})
export class DynamicService {

  constructor(
    private factory: ComponentFactoryResolver,
    private appRef: ApplicationRef,
    private injector: Injector,
    private doc: DocumentWrapperService
  ) { }
  generate(Container: any): ComponentRef<any> {
    const comp: ComponentRef<any> = this.factory.resolveComponentFactory(Container).create(this.injector);
    this.appRef.attachView(comp.hostView);

    const id = this.makeId();
    const hostElement: HTMLElement = this.doc.createElement('div')
    hostElement.setAttribute('id', id)
    comp.instance.id = id
    hostElement.appendChild((<any>comp.hostView).rootNodes[0])
    this.doc.body.appendChild(hostElement)

    return comp;
  }
  destroy(com: ComponentRef<any>): void {
    const timer = setTimeout(() => {
      this.destroyWait(com)
      clearTimeout(timer)
    }, 500)
  }

  destroyWait(com: ComponentRef<any>): void {
    const id = com.instance.id
    this.appRef.detachView(com.hostView)
    com.destroy()
    try {
      const hostElement = this.doc.getElementById(id)
      hostElement && hostElement.parentElement.removeChild(hostElement)
    } catch (err) {}
  }

  makeId() {
    return Math.random().toString(16).substr(2, 8)
  }
}
